import { useEffect, useRef } from 'react';

export function useListenClickOutside(callback: Fn) {
  const divRef = useRef<HTMLDivElement>(null);
  const callbackRef = useRef(callback);

  useEffect(() => {
    document.body.addEventListener('click', event => {
      const isOut = !(
        divRef.current && divRef.current.contains(event.target as Node)
      );
      if (isOut) {
        callbackRef.current?.();
      }
    });
  }, []);

  return divRef;
}
